import os
import sys

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////' + os.path.join(os.path.dirname(app.root_path),
                                                                     os.getenv('DATABASE_FILE', 'data.db'))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
login_manager = LoginManager(app)


@login_manager.user_loader
def load_user(user_id):
    from watchlist.models import User
    user = User.query.get(int(user_id))
    return user


login_manager.login_view = 'login'


# 这个函数返回的变量(以字典键值对的形式)将会统一注入到每一个模板的上下文环境中
@app.context_processor
def inject_user():
    from watchlist.models import User
    user = User.query.first()
    # 需要返回字典，等同于 return {'user': user}
    return dict(user=user)


# 避免循环依赖
from watchlist import views, errors, commands
